<template>
  <div class="weChat df fdc" id="we-chat">
    <a-empty
      :description="false"
      class="df aic jcc f1"
      v-if="messages.length === 0"
    />
    <div class="weChat-box" ref="weChatDom">
      <block
        class="pt10 pb10 df"
        :class="{
          rtl: selfChineseName === item.username
        }"
        v-for="item in messages"
        :key="item.gmtCreate"
      >
        <a-avatar style="background-color: #1890ff" shape="square">
          {{ showAvatar(item.username) }}
        </a-avatar>
        <div class="ml10 f1">
          <div class="df userInfo">
            <span class="nickName mr10 grey">{{ item.username }}</span>
            <span class="sendTime grey mr5">{{ handlerTime(item) }}</span>
            <a-popconfirm
              title="是否确认撤回?"
              ok-text="是"
              cancel-text="否"
              @confirm="revokeMessage(item)"
              v-if="selfChineseName === item.username && item.returnType === 0"
            >
              <span class="themeColor cp"> 撤回 <RollbackOutlined /></span>
            </a-popconfirm>
          </div>
          <div>
            <div
              v-html="item.remark"
              class="fl chatContent"
              style="direction: initial"
            ></div>
          </div>
        </div>
      </block>
    </div>
    <WangEditor @onSend="send" :readOnly="readOnly"></WangEditor>
  </div>
</template>
<script setup>
import { nextTick, ref, watch, defineAsyncComponent } from 'vue'
// import moment from 'moment'
import useAPI from 'UseApi'
import { createGlobalComponent } from '../createComponent.js'
import { RollbackOutlined } from '@ant-design/icons-vue'
import { message_board_message_recall_new_get } from 'server/modules/4788.js'
import { message } from 'ant-design-vue'
// 异步加载组件
const previewGroup = defineAsyncComponent(() => import('../previewGroup.vue'))

const APIS = useAPI(null, ['4788'])

const props = defineProps({
  bizId: {
    type: [Number, String]
  },
  bizType: {
    type: [Number, String]
  },
  readOnly: {
    type: Boolean,
    default: false
  }
})

const messages = ref([])

const weChatDom = ref(null)
// 用户名
const userName = localStorage.getItem('userName')?.split('-')
// 中文名称
const selfChineseName = userName
  ? userName?.length === 1
    ? userName[0]
    : userName[1]
  : ''

/**
 * 处理时间
 */
const handlerTime = item => {
  const times = item.gmtCreate.split(' ')
  let timestr = null
  if (times) {
    const dates = times[0]
    const datearr = dates.split('-')
    const time = times[1]
    const timearr = time.split(':')
    timestr =
      datearr[0] +
      '年' +
      datearr[1] +
      '月' +
      datearr[2] +
      '日' +
      ' ' +
      timearr[0] +
      ':' +
      timearr[1]
    return timestr
  }
  //下午时间转换有问题
  // const value = moment(new Date()).diff(moment(item.gmtCreate), 'hour')
  // if (value < 1) {
  //   moment()
  //     .startOf('seconds')
  //     .fromNow()
  // } else if (value < 24) {
  //   return moment(item.gmtCreate).format('hh:mm')
  // } else if (moment(item.gmtCreate).years() === moment().years()) {
  //   return moment(item.gmtCreate).format('MM月DD日 hh:mm')
  // } else {
  //   return item.gmtCreate
  // }
}
/**
 * 获取聊天信息
 */
const getMessageList = () => {
  APIS.message_board_list_remark_post_(
    {
      bizId: props.bizId,
      bizType: props.bizType
    },
    messages
  )
  setTimeout(scrollToBottom, 500)
}
/**
 * 发送信息
 */
const send = remark => {
  const userIds = []
  const doc = document.createRange().createContextualFragment(remark)
  const nodes = doc.querySelectorAll('[data-info]')
  nodes.length &&
    nodes.forEach(node => {
      const info = JSON.parse(decodeURIComponent(node.dataset.info))
      userIds.push(info.id)
    })
  APIS.message_board_add_remark_post_(
    {
      bizId: props.bizId,
      bizType: props.bizType,
      userIds,
      remark: remark.trim()
    },
    () => {
      getMessageList()
    }
  )
}
/**
 * 显示头像
 */
const showAvatar = userName => {
  if (userName?.length === 2) {
    return userName
  }
  return userName?.substr(-2, 2)
}
/**
 * 处理滚动条
 */
const scrollToBottom = () => {
  const domWrapper = weChatDom.value // 外层容器 出现滚动条的dom
  ;(function smoothscroll() {
    const currentScroll = domWrapper.scrollTop // 已经被卷掉的高度
    const clientHeight = domWrapper.offsetHeight // 容器高度
    const scrollHeight = domWrapper.scrollHeight // 内容总高度
    if (scrollHeight - 10 > currentScroll + clientHeight) {
      window.requestAnimationFrame(smoothscroll)
      domWrapper.scrollTo(
        0,
        currentScroll + 10 + (scrollHeight - currentScroll - clientHeight) / 2
      )
    }
  })()
}
const revokeMessage = async item => {
  const { success, retInfo } = await message_board_message_recall_new_get({
    id: item.id
  })
  if (success) {
    message.success(retInfo)
    getMessageList()
  } else {
    message.error(retInfo)
  }
}
watch(
  () => props.bizId,
  () => {
    getMessageList()
  },
  {
    immediate: true
  }
)
watch(
  () => messages.value,
  () => {
    if (messages.value.length > 0) {
      nextTick(() => {
        const imgNodes = document.querySelectorAll('.weChat-box img')
        imgNodes.forEach(item => {
          item.onclick = null
          item.onclick = e => {
            let root = createGlobalComponent(previewGroup, {
              visible: true,
              src: e.target.src,
              className: 'previewGroup',
              close: () => {
                root.remove()
                root = null
              }
            })
          }
        })
      })
    }
  }
)
</script>
<style lang="scss">
.weChat {
  background: #f5f5f9;
  font-size: 12px;
  font-family: system-ui;
  height: calc(100vh - 60px);
  // width: 480px;

  color: rgba(110, 81, 81, 0.85);
  position: relative;
  .themeColor {
    color: #1890ff;
  }
  span[data-w-e-type='mention'] {
    color: #1890ff;
  }

  &-box {
    overflow-y: auto;
    position: relative;
    flex: 1;
    padding: 0 12px;
    .userInfo {
      // .sendTime {
      //   display: none;
      // }
      // &:hover {
      //   .sendTime {
      //     display: inline-block;
      //   }
      // }
    }

    .memberList {
      min-width: 150px;
      max-height: 200px;
      overflow-y: auto;
      /* transform: translateY(-100%); */
      bottom: 0;
      z-index: 444;
      background: #fff;
      width: -moz-max-content;
      width: max-content;
      padding: 6px;
      position: absolute;
      .userImg {
        width: 30px;
        height: 30px;
        margin-right: 3px;
      }
    }

    .grey {
      color: rgba(0, 0, 0, 0.35);
    }

    .chatContent {
      background: #ffffff;
      border: 1px solid #e4e4e4;
      border-radius: 4px;
      /* display: flex;
      align-content: center;
      flex-wrap: wrap; */
      word-break: break-all;
      padding: 7px 10px;
      img {
        max-height: 150px !important;
      }
    }
    .rtl {
      direction: rtl;
      .fl {
        float: right;
      }
      .ml10 {
        margin-right: 10px;
      }
      .mr10 {
        margin-left: 10px;
      }
      .mr5 {
        margin-left: 5px;
      }
      .chatContent {
        text-align: left;
        background: #c9e7fe;
      }
    }
  }
}
</style>
